// miniprogram/pages/freeLearn1/freeLearn1.js
var httpUtils = require('../../utils/httpUtils')
var api = require("../../utils/API")
var innerAudioContext = null;
import {
  $wuxCountDown,
  $wuxDialog
} from '../../dist-wux/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    IMAGE_URL: httpUtils.IMAGE_URL,
    startTime: null, //开始答题时间
    isTestOver: false, //考试是否结束
    choosedSubject: 1, //所选择的科目
    questionList: [],
    totalCount: 0,
    correctCount: 0, //回答正确题目数
    errorCount: 0, //回答错误题目数
    answerList: [], //答案列表
    currentQuestion: null,
    currentQuestionIndex: 1,
    IsAnswerSheetOpen: false,
    IsExplanOpen: false,
    currentAnswer: {
      subIndex: 0,
      cusAnswer: '',
      IsAnswered: false,
      IsCorrect: true
    },
    optionAType: "md-radio-button-off",
    optionBType: "md-radio-button-off",
    optionCType: "md-radio-button-off",
    optionDType: "md-radio-button-off",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData({
      choosedSubject: options.subject
    });
    this.getQuestionsPagedList();
    var _this = this;
    var subjectOneInfo = "小车-C1/C2/C3科目一，考试时间45分钟，总分100分，每题1分，及格为90分。"
    var subjectFourInfo = "小车-C1/C2/C3科目四，考试时间30分钟，总分100分，每题2分，及格为90分。"
    $wuxDialog().alert({
      resetOnClose: true,
      title: '考试规则',
      content: _this.data.choosedSubject == 1 ? subjectOneInfo : subjectFourInfo,
      onConfirm(e) {
        _this.setData({
          startTime: new Date()
        })
        _this.startCountDown();
      },
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    if (innerAudioContext) {
      innerAudioContext.destroy();
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  startCountDown() {
    var _this = this;
    this.countDown = new $wuxCountDown({
      date: +(new Date) + 60000 * (this.data.choosedSubject == 1 ? 45 : 30),
      render(date) {
        const min = this.leadingZeros(date.min, 2) + ' 分 '
        const sec = this.leadingZeros(date.sec, 2) + ' 秒 '

        this.setData({
          countDown: '倒计时' + min + sec,
        })
      },
      onEnd() {
        console.log('end')
        _this.handIn('end');
      },
    })
  },
  getQuestionsPagedList() {
    var _this = this;
    httpUtils.postRequest(api.API_EXAM_LIST, {
      subject: _this.data.choosedSubject
    },
      res => {
        _this.initQuestions(res.data)
      },
      fail => {
        console.log(fail)
      }
    );
  },
  initQuestions(data) {
    console.log(data)
    var answerList = []
    for (let j = 0; j < data.length; j++) {
      answerList.push({
        subIndex: j,
        cusAnswer: "",
        IsAnswered: false,
        IsCorrect: true,
        IsJudge: data[j].QuesType == 3,
        Answer: data[j].Answer,
        showRightOrError: '' //判断答题卡显示什么
      });
    }
    this.setData({
      questionList: data,
      totalCount: data.length,
      currentQuestion: data[this.data.currentQuestionIndex - 1],
      answerList: answerList,
      currentAnswer: answerList[this.data.currentQuestionIndex - 1]
    })
  },
  //提交一次答题的记录
  examSingle(id, answer) {
    httpUtils.postRequest(api.API_EXAM_SINGLE, {
      id: id,
      answer: answer,
    },
      res => {
        console.log(res)
      },
      fail => {
        console.log(fail)
      }
    );
  },
  //选择按钮
  tapAnswer: function (e) {
    if (this.data.isTestOver) {
      return
    }
    var option = e.currentTarget.dataset.index;
    // 没有回答
    if (!this.data.currentAnswer.IsAnswered) {
      if (this.data.currentQuestion.QuesTypeText !== '多选') {
        var cusAnswer = 'answerList[' + (this.data.currentQuestionIndex - 1) + '].cusAnswer';
        var IsCorrect = 'answerList[' + (this.data.currentQuestionIndex - 1) + '].IsCorrect';
        var IsAnswered = 'answerList[' + (this.data.currentQuestionIndex - 1) + '].IsAnswered';

        var IsCorrectValue = this.data.currentQuestion.Answer === option;
        var showRightOrError = 'answerList[' + (this.data.currentQuestionIndex - 1) + '].showRightOrError';
        var showRightOrErrorVal = '';
        if (this.data.currentQuestion.QuesTypeText !== '判断') {
          showRightOrErrorVal = IsCorrectValue;
        } else {
          showRightOrErrorVal = this.data.currentQuestion.Answer == 'A';
        }
        this.setData({
          [cusAnswer]: option,
          [IsCorrect]: IsCorrectValue,
          [IsAnswered]: true,
          [showRightOrError]: showRightOrErrorVal
        })
        this.setData({
          currentAnswer: this.data.answerList[this.data.currentQuestionIndex - 1]
        });

        this.setData({
          optionAType: this.answerOptionClass('A'),
          optionBType: this.answerOptionClass('B'),
          optionCType: this.answerOptionClass('C'),
          optionDType: this.answerOptionClass('D'),
        });
        //向后台提交答题记录
        this.examSingle(this.data.currentQuestion.Id, IsCorrectValue ? 1 : 2);

        //回答以后的统计
        if (IsCorrectValue) { //回答正确到下一题
          this.setData({
            correctCount: this.data.correctCount + 1,
          });

          let _this = this;
          setTimeout(function () {
            _this.nextQuestion();
          }, 500)
        } else {
          this.playAudio();
          this.setData({
            errorCount: this.data.errorCount + 1,
          })
        }
        //计算选择

      } else {
        if (!this.data.currentAnswer.cusAnswer.includes(option)) {
          var cusAnswer = 'answerList[' + (this.data.currentQuestionIndex - 1) + '].cusAnswer';
          var cusAnswerValue = this.data.currentAnswer.cusAnswer + option + ","
          this.setData({
            [cusAnswer]: cusAnswerValue
          });
          this.setData({
            currentAnswer: this.data.answerList[this.data.currentQuestionIndex - 1]
          });
          if (option == "A") {
            this.setData({
              optionAType: this.answerOptionClass('A')
            });
          } else if (option == "B") {
            this.setData({
              optionBType: this.answerOptionClass('B')
            });
          } else if (option == "C") {
            this.setData({
              optionCType: this.answerOptionClass('C')
            });
          } else if (option == "D") {
            this.setData({
              optionDType: this.answerOptionClass('D')
            });
          }
        }
      }

    }
  },
  //提交多选的答案
  submitAnswers() {
    if (this.data.isTestOver) {
      return
    }
    if (this.data.currentQuestion.QuesTypeText === "多选") {
      let cusAnswer = this.data.currentAnswer.cusAnswer
        .substring(0, this.data.currentAnswer.cusAnswer.length - 1)
        .split(",");
      let subjectAnswer = this.data.currentQuestion.Answer.split(",");
      var IsCorrectValue = cusAnswer.sort().toString() === subjectAnswer.sort().toString();
      var IsCorrect = 'answerList[' + (this.data.currentQuestionIndex - 1) + '].IsCorrect';
      var IsAnswered = 'answerList[' + (this.data.currentQuestionIndex - 1) + '].IsAnswered';

      var showRightOrError = 'answerList[' + (this.data.currentQuestionIndex - 1) + '].showRightOrError';
      var showRightOrErrorVal = IsCorrectValue;

      this.setData({
        [IsCorrect]: IsCorrectValue,
        [IsAnswered]: true,
        [showRightOrError]: showRightOrErrorVal
      });
      //向后台提交答题记录
      this.examSingle(this.data.currentQuestion.Id, IsCorrectValue ? 1 : 2);
      //回答以后的统计
      if (IsCorrectValue) { //回答正确到下一题
        this.setData({
          correctCount: this.data.correctCount + 1,
        });

        let _this = this;
        setTimeout(function () {
          _this.nextQuestion();
        }, 500)
      } else {
        this.playAudio();
        this.setData({
          errorCount: this.data.errorCount + 1,
        })
      }
      this.setData({
        optionAType: this.answerOptionClass('A'),
        optionBType: this.answerOptionClass('B'),
        optionCType: this.answerOptionClass('C'),
        optionDType: this.answerOptionClass('D'),
      });
    }
  },
  answerOptionClass: function (option) {
    let className = 'md-radio-button-off';
    if (this.data.currentQuestion.QuesTypeText === '多选') {
      if (this.data.currentAnswer.IsAnswered) { //已经提交答案
        if (this.data.currentQuestion.Answer.includes(option) && this.data.currentAnswer.cusAnswer.includes(option)) { //答案里有这个选项 且 选择了这个选项
          className = 'md-checkmark-circle'
        } else if (this.data.currentQuestion.Answer.includes(option) && !this.data.currentAnswer.cusAnswer.includes(option)) { //答案里有  但  没选
          className = 'md-checkmark-circle-outline'
        } else if (!this.data.currentQuestion.Answer.includes(option) && this.data.currentAnswer.cusAnswer.includes(option)) { //答案里没有 但 选了
          className = 'md-close-circle'
        }
      } else { //没有提交答案的如果选过
        if (this.data.currentAnswer.cusAnswer.includes(option)) {
          className = 'md-checkmark-circle'
        }
      }
    } else {
      if (this.data.currentAnswer.IsAnswered) {
        if (this.data.currentQuestion.Answer.includes(option)) {
          className = 'md-checkmark-circle'
        } else if (!this.data.currentQuestion.Answer.includes(option) && this.data.currentAnswer.cusAnswer.includes(option)) {
          className = 'md-close-circle'
        }
      }
    }
    return className

  },
  preQuestion() {
    if (innerAudioContext) {
      innerAudioContext.destroy();
    }
    if (this.data.currentQuestionIndex > 1) {
      this.setData({
        currentQuestionIndex: this.data.currentQuestionIndex - 1,
      })
      this.setData({
        currentQuestion: this.data.questionList[this.data.currentQuestionIndex - 1],
        currentAnswer: this.data.answerList[this.data.currentQuestionIndex - 1],
      })
      this.setData({
        optionAType: this.answerOptionClass('A'),
        optionBType: this.answerOptionClass('B'),
        optionCType: this.answerOptionClass('C'),
        optionDType: this.answerOptionClass('D'),
      });

    }
  },
  nextQuestion() {
    if (innerAudioContext) {
      innerAudioContext.destroy();
    }
    if (this.data.currentQuestionIndex !== this.data.totalCount) {
      this.setData({
        currentQuestionIndex: this.data.currentQuestionIndex + 1,
      })
      this.setData({
        currentQuestion: this.data.questionList[this.data.currentQuestionIndex - 1],
        currentAnswer: this.data.answerList[this.data.currentQuestionIndex - 1],
      })
      this.setData({
        optionAType: this.answerOptionClass('A'),
        optionBType: this.answerOptionClass('B'),
        optionCType: this.answerOptionClass('C'),
        optionDType: this.answerOptionClass('D'),
      });

    }
  },
  turnTo(e) {
    if (innerAudioContext) {
      innerAudioContext.destroy();
    }
    var index = e.currentTarget.dataset.index;
    if (index !== this.data.currentQuestionIndex) {
      this.setData({
        currentQuestionIndex: index,
      })
      this.setData({
        currentQuestion: this.data.questionList[this.data.currentQuestionIndex - 1],
        currentAnswer: this.data.answerList[this.data.currentQuestionIndex - 1],
      })
      this.setData({
        optionAType: this.answerOptionClass('A'),
        optionBType: this.answerOptionClass('B'),
        optionCType: this.answerOptionClass('C'),
        optionDType: this.answerOptionClass('D'),
      });

    }
  },
  //打开答题板
  showAnswerSheet() {
    this.setData({
      IsAnswerSheetOpen: true
    });
  },
  onCloseAnswerSheet() {
    this.setData({
      IsAnswerSheetOpen: false
    });
  },
  //打开讲解
  showExplan() {
    this.setData({
      IsExplanOpen: true
    });
  },
  onCloseExplan() {
    this.setData({
      IsExplanOpen: false
    });
  },
  //交卷
  handIn(isEnd) {
    if (!this.data.isTestOver) {
      this.countDown.stop();
      this.setData({
        countDown: '考试结束',
        isTestOver: true
      })
      var endTime = this.data.startTime;
      var examMinute = 0;
      var subject = this.data.choosedSubject;
      var correct = this.data.correctCount;
      var wrong = this.data.errorCount;
      var score = this.data.correctCount * 100 / this.data.totalCount;
      //如果是到时间自动交卷子的
      if (isEnd == 'end') {
        examMinute = this.data.choosedSubject == 1 ? 45 : 30;
        endTime.setMinutes(endTime.getMinutes() + examMinute, endTime.getSeconds(), 0);
      } else {
        endTime = new Date();
        examMinute = Math.floor((endTime.getTime() - this.data.startTime.getTime()) / 1000 / 60)
      }
      var _this = this;
      httpUtils.postRequest(api.API_HAND_IN_EXAM, {
        correct: correct,
        wrong: wrong,
        score: score,
        subject: subject,
        startTime: _this.formatDate(_this.data.startTime),
        endTime: _this.formatDate(endTime),
        examMinute: examMinute
      },
        res => {
          if (res.code == 0) {
            wx.navigateTo({
              url: api.PAGES_TEST_RESULT + "?subject=" + subject + "&correct=" + correct + "&wrong=" + wrong + "&score=" + score + "&examMinute=" + examMinute
            })
          }

        },
        fail => {
          console.log(fail)
        }
      );
    }



  },
  formatDate(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    minute = minute < 10 ? ('0' + minute) : minute;
    var second = date.getSeconds();
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
  },
  //播放音频
  playAudio() {
    if (this.data.currentQuestion.ExpAudio) {
      if (innerAudioContext) {
        innerAudioContext.destroy();
      }
      innerAudioContext = wx.createInnerAudioContext();
      innerAudioContext.autoplay = true
      innerAudioContext.src = this.data.IMAGE_URL + this.data.currentQuestion.ExpAudio;
      console.log(this.data.IMAGE_URL + this.data.currentQuestion.ExpAudio)

      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })
      innerAudioContext.onError((res) => {
        console.log(res.errMsg)
        console.log(res.errCode)
      })
    }

  }
})